<script setup lang="ts">
import { postLoginWxMinAPI, postLoginWxMinSimpleAPI } from '@/services/login'
import { useMemberStore } from '@/stores'
import type { LoginResult } from '@/types/member'
import { Mcaptcha } from '@/utils/mcaptcha'
import { onLoad, onReady, onShow } from '@dcloudio/uni-app'
import { ref, reactive, onMounted, toRaw } from 'vue'
import { useI18n } from 'vue-i18n'
import { login } from '@/api/login'
import { uploadImage } from '@/api/login'
import { RSA_encryption, rsaEncryptSet, RSA_encryption1, md5Str } from '@/utils/index'
import Rsa from '@/utils/rsa_s.js'
import VConsole from 'vconsole'

const { t, locale } = useI18n()
const timeNumber = ref(60)
const isGetCode = ref(false)
const showLanguage = ref(false) // 弹出语言窗
const memberStore = useMemberStore()
const popup = ref() // 弹窗ref
const currentLanguage = ref<any>({})
const paramsData = reactive({data: {}}) // 路径参数

const hideShooting = ref<boolean>(false); // 显示按钮

const cameraInput = ref<any>();
const languageList = reactive({
  // zh_CN,en_US,th_TH,vi_VN
  list: [
    {
      type: 'zh_CN',
      name: t('loginIndex.Chinese'),
      id: '1',
      icon: '../../static/image/china-icon.png',
    },
    {
      type: 'en_US',
      name: t('loginIndex.English'),
      id: '2',
      icon: '../../static/image/english-icon.png',
    },
    // {
    //   type: 'French',
    //   name: t('loginIndex.French'),
    //   id: '3',
    //   icon: '../../static/image/french-icon.png',
    // },
    // {
    //   type: 'Japan',
    //   name: t('loginIndex.Japanese'),
    //   id: '4',
    //   icon: '../../static/image/japanese-icon.png',
    // },
    // {
    //   type: 'Korean',
    //   name: t('loginIndex.Korean'),
    //   id: '5',
    //   icon: '../../static/image/Korean-icon.png',
    // },
  ],
}) // 语言列表
const vConsole = new VConsole()
// #ifdef MP-WEIXIN
// 获取 code 登录凭证
let code = ''
onLoad(async () => {
  // const res = await wx.login()
  // code = res.code
})
onShow(() => {
  console.log(' onShow 开启调试')
  // #ifdef H5 || WEB
  var queryString = window.location.search;
  queryString = queryString.substring(1);
  var params = queryString.split('&');
  var queryParams:any = {};
  params.forEach((param) => {
    var parts = param.split('=');
    queryParams[parts[0]] = parts[1];
  });
  paramsData.data = queryParams; 
  console.log(' - - > camera : ', queryParams);
  // #endif

})
const video = ref(null);
const canvas = ref(null);
onMounted(() => {
    console.log('onMounted 开启调试')
  
})
// 打开前置摄像头
const openForent = () => {
   navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" }  })
    .then(stream => {
      video.value.srcObject = stream;
    })
    .catch(error => {
      console.error("摄像头访问失败:", error);
      uni.showModal({
        title: "提示",
        content: "请检查是否已打开摄像头权限",
        showCancel: false
      });
    });
}
// 获取用户手机号码
const onGetphonenumber: UniHelper.ButtonOnGetphonenumber = async (ev) => {
  // await checkedAgreePrivacy()
  // const { encryptedData, iv } = ev.detail
  // const res = await postLoginWxMinAPI({ code, encryptedData, iv })
  // loginSuccess(res.result)
}
// #endif
// 模拟手机号码快捷登录（开发练习）
// const onGetphonenumberSimple = async () => {
//   await checkedAgreePrivacy()
//   const res = await postLoginWxMinSimpleAPI('13123456789')
//   loginSuccess(res.result)
// }

const loginSuccess = (profile: LoginResult) => {
  // 保存用户信息
  memberStore.setProfile(profile)
  // 成功提示
  // uni.showToast({ icon: 'success', title: '登录成功' })
  setTimeout(() => {
    // 页面跳转
    uni.switchTab({ url: '/pages/index/index' })
    //uni.navigateBack()
  }, 100)
}

// #ifdef H5 || APP-PLUS
const myForm = ref()
const formArea = ref<{ account: string; password: string; googleCode: string }>({
  account: 'adminone',
  password: 'adminone',
  googleCode: '',
})
// 定义校验规则
const rules: UniHelper.UniFormsRules = {
  account: {
    rules: [{ required: true, errorMessage: t('loginIndex.tipphone') }],
  },
  password: {
    rules: [{ required: true, errorMessage: t('loginIndex.tippassword') }],
  },
  googleCode: {
    rules: [{ required: true, errorMessage: t('loginIndex.googlevertifyCode') }],
  },
}
const mcaptcha = ref() // 验证码
onReady(() => {
  //   mcaptcha.value = new Mcaptcha({
  //     el: 'canvas',
  //     width: 90,
  //     height: 40,
  //     createCodeImg: '',
  //   })
})
// 刷新验证码
const updateImageCode = () => {
  mcaptcha.value.refresh()
}
onMounted(() => {
  let lang = memberStore.language
  if (lang) {
    currentLanguage.value = toRaw(languageList.list).find((item) => item.type === lang)
  }
  // let params = {
  //   langguage: memberStore.language,
  //   timestamp: 'test data',
  //   sign: 'sign data',
  //   data: 'data data',
  //   userId: 'userId data',
  //   token: 'token data',
  //   deviceId: 'deviceId data',
  // }
  // // RSA_encryption1(params)

  // let res = Rsa.encrypt(params)
  // let request_id = +new Date();
  // let m5 = md5Str(request_id)
  // console.log('Rsa.encrypt 333:', m5)
})
// 提交前校验图形验证码

// 表单提交

const onSubmit = async () => {
  uni.switchTab({ url: '/pages/index/index' })
}
//const onSubmit = async () => {
//  if (!formArea.value.codeNmuber) {
//    return uni.showToast({ title: '请输入图形验证码',icon: 'none' })
//  }
//  let validate = mcaptcha.value.validate(formArea.value.codeNmuber)
//  //console.log(' - - -> code ', formArea.value.codeNmuber, validate)
//  if (!validate) {
//    return uni.showToast({ title: '图形验证码错误',icon: 'error' })
//  } else {
//    // 图形验证码正确
//    //await checkedAgreePrivacy()
//    //const res = await postLoginAPI(form.value)
//    //loginSuccess(res.result)
//  }
//}
// #endif

// 请先阅读并勾选协议
const isAgreePrivacy = ref(false)
const isAgreePrivacyShakeY = ref(false)
const checkedAgreePrivacy = async () => {
  //   if (!isAgreePrivacy.value) {
  //     uni.showToast({
  //       icon: 'none',
  //       title: '请先阅读并勾选协议',
  //     })
  //     // 震动提示
  //     isAgreePrivacyShakeY.value = true
  //     setTimeout(() => {
  //       isAgreePrivacyShakeY.value = false
  //     },500)
  //     // 返回错误
  //     return Promise.reject(new Error('请先阅读并勾选协议'))
  //   }
}
const onOpenPrivacyContract = () => {
  // #ifdef MP-WEIXIN
  // 跳转至隐私协议页面
  // wx.openPrivacyContract({})
  // #endif
}

// 下一步
const nextCb = () => {
  // if (!formArea.value.account) {
  //   uni.showToast({ title: t('loginIndex.account'), icon: 'none' })
  //   return
  // }
  // if (!new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(formArea.value.account)) {
  //   uni.showToast({ title: t('loginIndex.account'), icon: 'none' })
  //   return
  // }
  // if (!formArea.value.password) {
  //   uni.showToast({ title: t('loginIndex.tippassword'), icon: 'none' })
  //   return
  // }
  // if (!formArea.value.googleCode) {
  //   uni.showToast({ title: t('loginIndex.googlevertifyCode'), icon: 'none' })
  //   return
  // }
  // uni.showLoading({
  //   title: t('more.loading'),
  //   mask: true,
  // })
  // let obj = {
  //   googleCode: formArea.value.googleCode,
  //   language: currentLanguage.value.type,
  //   password: formArea.value.password,
  //   userName: formArea.value.account,
  // }
  // let encryptStr = RSA_encryption(obj)
  // let encryptStr = rsaEncryptSet(obj)
  // login(obj)
  //   .then((res: any) => {
  //     console.log('login', res)
  //     // code: 0
  //     // expireTime: "2025-03-31 15:20:56"
  //     // loginTime: "2025-03-30 15:20:56"
  //     // msg: "操作成功"
  //     // scorerNo: "666666"
  //     // token: "a7a787b208a92f40755f7106f5ccf92d"
  //     // userName: "adminone"

  //     if (res && res.code == 0) {
  //       memberStore.setProfile({
  //         expireTime: res.expireTime,
  //         loginTime: res.loginTime,
  //         scorerNo: res.scorerNo,
  //         token: res.token,
  //         userName: res.fullName,
  //         budingStatus: res.budingStatus, // 1未绑定  2已经绑定
  //       })
  //       // uni.showToast({ title: t('loginIndex.loginSuccess'), icon: 'none' })
  //       // 存储用户信息数据到本地
  //       // uni.setStorageSync('userInfo', res)
  //       if (res.budingStatus == 1) {
  //         // 跳转绑定页
  //         uni.redirectTo({ url: '/pages/login/loginMail' })
  //       } else if (res.budingStatus == 2) {
  //         uni.showToast({ title: t('loginIndex.loginSuccess'), icon: 'none' })
  //         // 跳转到首页
  //         uni.switchTab({
  //           url: '/pages/home/index',
  //         })
  //         // uni.redirectTo({ url: '/pages/home/index' })
  //       }
  //     } else {
  //       uni.showToast({ title: res?.msg || t('loginIndex.loginFail'), icon: 'none' })
  //     }
  //   })
  //   .catch((err) => {
  //     uni.showToast({ title: err?.msg || t('loginIndex.loginFail'), icon: 'none' })
  //     console.log('err - - - >', err)
  //   })
  // 隐藏
  // uni.hideLoading()
}

// 选择语言
const selectLan = () => {
  popup.value.open('bottom')
}
const changePopup = (e) => {
  console.log('当前模式：' + e.type + ',状态：' + e.show)
}
const closePopup = () => {
  popup.value.close()
}
// 选择语言
const changeLanguage = (item) => {
  currentLanguage.value = item
  memberStore.setLanguage(item.type)
  // uni.setStorageSync('language', item.type)
  // i18n.locale = item.type
  uni.$emit('i18nChange')
  popup.value.close()
  // #ifdef H5
  window.location.reload()
  // #endif
  // #ifdef MP-WEIXIN || APP-PLUS
  uni.reLaunch({ url: '/pages/login/loginPass' })
  // #endif
}
// 修改图片颜色
const imgPath = (path: string) => {
  const platform = process.env.VUE_APP_PLATFORM
  return platform == 'h5' ? `../../static/image/${path}` : `@/static/image/${path}`
}
const getBse64Url = () => {
  uni.chooseImage({
  count: 1, // 默认9
  sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
  sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
  success: function (res) {
    const tempFilePaths = res.tempFilePaths;
    console.log(' - - - > tempFilePaths', tempFilePaths);
    uploadImage(tempFilePaths[0]); // 上传图片或进行其他操作
  }
});
 
}
// const uploadImage = (filePath) => {
//   const fileManager = uni.getFileSystemManager();
//   fileManager.readFile({
//     filePath: filePath, // 选择图片返回的相对路径
//     encoding: 'base64', // 返回Base64编码
//     success: res => {
//       const base64 = res.data; // 得到的base64字符串
//       console.log(base64); // 输出或使用base64字符串
//       // 这里可以将base64字符串发送到服务器等操作，例如：uploadToServer(base64);
//     },
//     fail: err => {
//       console.error('读取文件失败', err);
//     }
//   });
// }
const handlePhotographCloseClick = () => {

}
// 
const handlePhotographClick =() => {

}
// 
const handleAddPhotographClick = () => {

}
// 开始拍摄
const startCamera = () => { 
  // 在页面的 JS 文件中
  uni.chooseImage({
    count: 1, // 默认拍照数量
    sourceType: ['camera'], // 只能从相机选择
    camera: 'front', // 使用前置摄像头
    success: (res) => {
      const tempFilePaths = res.tempFilePaths;
      console.log(tempFilePaths[0]); // 输出图片的本地文件路径列表
      // 这里可以将图片路径显示在页面上或上传到服务器
    },
    fail: (err) => {
      console.error(err);
    }
  });
}
// 摄像头
const handleCamera = (event:any) => {
  // 获取文件列表
  const files = event.target.files;
  if (files.length > 0) {
    // 获取第一张图片
    const imageFile = files[0];
    // 可以将图片转换为base64或者上传到服务器等操作
    const reader = new FileReader();
    reader.readAsDataURL(imageFile);
    reader.onload = (e) => {
      const base64Image = e.target.result;
      console.log(base64Image); // 输出图片的base64编码
      // 这里可以进行后续处理，如显示图片、上传等
    };
  }
}
const triggerCamera = () => {
  // 触发相机
  const cameraInp = cameraInput.value;
  cameraInp.click();
}
// 拍照片
const takePhoto = () => {
  const context = canvas.value.getContext('2d');
  context.drawImage(video.value, 0, 0, canvas.value.width, canvas.value.height);
  const imageDataURL = canvas.value.toDataURL('image/png');
  console.log("图片数据URL:", imageDataURL);
  // 这里可以处理图片数据，例如显示或者上传等
  putbaseData(imageDataURL);
}
// 获取
const putbaseData = (image:string) => {
  let params = {
    mobile: paramsData.data.mobile || '',
    order: paramsData.data.order || '',
    image: image || ''
  }
  uploadImage(params).then(res => {
    if (res && res.code === 200) {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      });
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      });
    }
  }).catch(err => {
    console.log('err :', err)
    uni.showToast({
      title: err.msg,
      icon: 'none'
    });
  })
}

const startShooting = () => { 
    hideShooting.value = true;
   
    openForent();
}

</script>
<template>
  <view class="" style="width: 100vw;height: 100vh;background-color: #fff;">
    <!-- <video
      style="width: 100vw;height:calc(100vh - 240rpx);"
      object-fit="fill"
    ></video> -->
      <view
        class="wrap-content"
        style="width: 100vw;height: 100vh;background-color: transparent;opacity: 1;position: absolute;top: 0; left: 0;z-index: 1;"
      >
      <!-- <button @click="triggerCamera">拍照</button> -->
      <!-- <input type="file" accept="image/*" capture="camera" style="display: none;" @change="handleCamera" :ref="cameraInput"> -->
      <!-- <input type="file" accept="image/*" capture="camera" @change="handleCamera"> -->
      <!-- <view class="start-btn" @click="startCamera">Start shooting</view> -->
      <view class="video-wrap-cont flexC">
        <view v-if="!hideShooting" class="start-btn" @click="startShooting">
          Start shooting
        </view>
        <video v-if="video" class="video-wrap" ref="video" autoplay></video>
        <button class="take-photo-btn" @click="takePhoto">上传</button>
        <canvas ref="canvas" style="display:none;"></canvas>
      </view>  
      <!-- <video id="video" style="width: 100%; height: auto;"></video> -->

        <!-- <view
          class="flex justify-center align-center"
          style="width: 100vw;height: 100vh;position: absolute;top: 0; left: 0;z-index: 2;"
        >
          <image
            src="@/static/image/GcashValidFace.jpg"
            mode="widthFix"
            style="width: 600rpx;margin-top: -200rpx;"
          ></image>
        </view>
        <view
          class="flex justify-center align-center"
          style="width: 100vw;height: 100vh;position: absolute;top: 0; left: 0;z-index: 3;"
        >
          <image
            src="@/static/image/GcashValidFace.jpg"
            mode="widthFix"
            style="width: 500rpx;margin-top: -200rpx;"
          ></image>
        </view> -->
  
        <!-- <view
          class="flex justify-center"
          style="width: 100vw;height: 100vh;position: absolute;top: 0; left: 0;z-index: 5;"
        >
          <view
            class=""
            style="position: absolute;bottom: 88rpx;left: 68rpx; color: #fff;font-weight: bold;background: #fff;border-radius: 16rpx;"
          >
            <uni-icons
              type="close"
              :size="32"
              @click="handlePhotographCloseClick"
            >
            </uni-icons>
          </view>
          <view
            class="outer-ring"
            style="position: absolute;bottom: 40rpx;"
            @click="handlePhotographClick"
          >
            <view class="middle-ring">
              <view class="inner-ring"></view>
            </view>
          </view>
          <view
            class=""
            style="position: absolute;bottom: 88rpx;right: 68rpx; color: #fff;font-weight: bold;background: #fff;border-radius: 16rpx;"
          >
            <uni-icons
              type="folder-add"
              :size="32"
              @click="handleAddPhotographClick"
            >
            </uni-icons>
          </view>
        </view> -->
      </view>
  </view>
</template>
<style lang="scss">
page {
  height: 100%;
}
.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
  background: #ffffff;
  background: red;
}
.wrap-content {
  padding-top: 45%;
}
.video-wrap {
  width: 150rpx;
  height: 150rpx;
  border-radius: 80rpx;
}
.btn_verification {
  display: inline-flex;
  padding: 30rpx;
  justify-content: center;
  align-items: center;
  gap: 20rpx;
  width: 40%;
  height: 104rpx;
  line-height: 104rpx;
  border-radius: 20rpx;
  text-align: center;
  background: #1773ff;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
}
.time-num {
  font-size: 32rpx;
  font-weight: 600;
  color: #999999;
}
.form-bet {
  justify-content: space-between;
}
.image_bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 0;
}
.login_txt_wrap {
  position: relative;
  z-index: 2;
  margin-top: 250rpx;
}
.login_txt {
  color: #0a2f4d;
  font-family: 'Alibaba PuHuiTi 3.0';
  font-size: 70rpx;
  font-weight: bolder;
  height: 98rpx;
  line-height: 98rpx;
}
.login_subtxt {
  color: #0a2f4d40;
  height: 42rpx;
  line-height: 42rpx;
  font-family: 'PingFang SC';
  font-size: 30rpx;
  font-style: normal;
  font-weight: 400;
  letter-spacing: 0.3rpx;
}
.select_lan {
  margin-bottom: 50rpx;
  justify-content: flex-start;
}
.image_lan {
  width: 28rpx;
  height: 28rpx;
  margin-left: 5rpx;
}
.login {
  display: flex;
  flex-direction: column;
  margin-top: 80rpx;
  padding: 10rpx 20rpx 20rpx;
  .input_wrap {
    width: 100%;
    height: 104rpx;
    line-height: 104rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    border: 1px solid #ddd;
    padding-left: 30rpx;
    margin-bottom: 10rpx;
    border-radius: 20rpx;
    border: 2rpx solid #eaeaea;
    background: #f0f5f9;
  }

  .next-wrap {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 90rpx;
  }
  .next-btn {
    width: 650rpx;
    height: 110rpx;
    border-radius: 20rpx;
    background: #1773ff;
    text-align: center;
    box-shadow: 0 18px 48px 0 #0000001a, 0 22px 48px 0 #00000014;
    color: #ffffff;
    font-family: 'PingFang SC';
    font-size: 32rpx;
    font-style: normal;
    font-weight: 600;
    line-height: 110rpx;
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    color: #fff;

    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .phone {
    background-color: #019aff;
  }
  .wechat {
    background-color: #06c05f;
  }

  .extra {
    flex: 1;
    padding: 70rpx 70rpx 0;

    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #999;
      position: relative;

      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;

      button {
        padding: 0;
        background-color: transparent;

        &::after {
          border: none;
        }
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }

    .icon-weixin::before {
      border-color: #019aff;
      color: #019aff;
    }
  }
  .input_wrap_ {
    width: 55%;
    margin-bottom: 0;
  }
}

.form-item-image {
  .uni-forms-item__content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;

    .image-code {
      width: 55%;
      display: inline-block;
    }

    .code-img-wrapper {
      display: inline-block;
    }
  }
}

@keyframes animate__shakeY {
  0% {
    transform: translate(0, 0);
  }

  50% {
    transform: translate(0, -5rpx);
  }

  100% {
    transform: translate(0, 0);
  }
}

.animate__shakeY {
  animation: animate__shakeY 0.2s ease-in-out 3;
}
.popup-content {
  border-top-left-radius: 10rpx;
  border-top-right-radius: 10rpx;
}
.popup-content-head {
  height: 124rpx;
  position: relative;
  border-bottom: 2rpx solid #eaeaea;
}
.head-txt {
  color: #07133b;
  text-align: center;
  font-family: 'PingFang SC';
  font-size: 34rpx;
  font-style: normal;
  font-weight: 500;
}
.image_close_ {
  position: absolute;
  top: 36rpx;
  right: 30rpx;
  width: 48rpx;
  height: 48rpx;
}
.button-privacy-wrap {
  position: relative;

  .button-opacity {
    opacity: 0;
    position: absolute;
    z-index: 1;
  }
}
.image_coun {
  width: 48rpx;
  height: 48rpx;
  margin-right: 20rpx;
}
.list-wrap {
  padding-bottom: 200rpx;
}
.item-lef-txt {
  color: #0a2f4d;
  font-family: 'PingFang SC';
  font-size: 32rpx;
  font-weight: 400;
}
.language-item {
  width: calc(100% - 40rpx);
  height: 120rpx;
  margin-left: 40rpx;
  padding-right: 40rpx;
  border-bottom: 2rpx solid #eaeaea;
  justify-content: space-between;
}
.image_coun_select {
  width: 40rpx;
  height: 40rpx;
  margin-right: 0rpx;
}
.tips {
  position: absolute;
  bottom: 80rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;

  .radio {
    transform: scale(0.6);
    margin-right: -4rpx;
    margin-top: -4rpx;
    vertical-align: middle;
  }

  .link {
    display: inline;
    color: #019aff;
  }
}
.start-btn {
  color: #fff;
  font-size: 22rpx;
  background: blue;
}
.take-photo-btn {
  margin-top: 200rpx;  
  background-color: blue;
  color: #ffffff;
  padding: 15rpx 50rpx;
  border-radius: 8rpx;

}
</style>
